package com.muatocroi.tornado;

import java.net.DatagramSocket;
import java.util.LinkedList;
import java.util.Queue;

import android.util.Log;

public class SignalSender {

	public static int password = 0;
	private DatagramSocket dSocket;
	private Queue<CommandSignal> sendQueue = new LinkedList<CommandSignal>();
	private Thread threadSender = null;
	private boolean stopThread = false;
	private static SignalSender instance = null;
	private boolean sending = false;

	public static SignalSender getSender() {
		if (instance == null)
			instance = new SignalSender();
		return instance;
	}

	private SignalSender() {
		Init();
	}

	public boolean isSending() {
		return sending;
	}

	void Init() {
		try {
			dSocket = new DatagramSocket(4444);
			dSocket.setBroadcast(true);
		} catch (Exception e) {
			Log.i("", e.getMessage());
		}
	}

	public void Send(CommandSignal cmd) {
		sendQueue.add(cmd);
	}

	public void BeginSend() {
		if (threadSender == null) {
			stopThread = false;
			threadSender = new Thread(new ThreadRun(), "Thread Sender");
			threadSender.start();
			sending = true;
		}
	}

	public void StopSend() {
		stopThread = true;
		try {
			threadSender = null;
		} catch (Exception e) {
			Log.i("", e.getMessage());
		}
		threadSender = null;
		sending = false;
	}

	class ThreadRun implements Runnable {

		@Override
		public void run() {
			while (!stopThread) {
				if (!sendQueue.isEmpty()) {
					try {
						dSocket.send(sendQueue.poll().ToPacket());
						System.out.println("Just Send >>>>>>>>>>>>> ");
					} catch (Exception e) {
					}
				}
			}
		}

	}

	public int getPassword() {
		return password;
	}

	public void setPassword(int password) {
		SignalSender.password = password;
	}
}
